package com.qyhl.module_practice.substreet.fragment_new;

import android.annotation.SuppressLint;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.inputmethod.EditorInfo;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.Spinner;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.recyclerview.widget.RecyclerView;
import androidx.recyclerview.widget.StaggeredGridLayoutManager;

import com.bumptech.glide.Glide;
import com.bumptech.glide.request.RequestOptions;
import com.qyhl.module_practice.R;
import com.qyhl.module_practice.R2;
import com.qyhl.webtv.basiclib.base.BaseFragment;
import com.qyhl.webtv.basiclib.utils.NetUtil;
import com.qyhl.webtv.basiclib.utils.StringUtils;
import com.qyhl.webtv.commonlib.constant.ARouterPathConstant;
import com.qyhl.webtv.commonlib.entity.civilized.PracticeListBean;
import com.qyhl.webtv.commonlib.utils.router.RouterManager;
import com.scwang.smartrefresh.header.MaterialHeader;
import com.scwang.smartrefresh.layout.SmartRefreshLayout;
import com.scwang.smartrefresh.layout.api.RefreshLayout;
import com.scwang.smartrefresh.layout.footer.ClassicsFooter;
import com.scwang.smartrefresh.layout.listener.OnLoadMoreListener;
import com.scwang.smartrefresh.layout.listener.OnRefreshListener;
import com.weavey.loading.lib.LoadingLayout;
import com.zhy.adapter.recyclerview.CommonAdapter;
import com.zhy.adapter.recyclerview.MultiItemTypeAdapter;
import com.zhy.adapter.recyclerview.base.ViewHolder;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.OnClick;

public class SubStreetNewFragment extends BaseFragment implements SubStreetNewContract.SubStreetNewView {
    @BindView(R2.id.recycle_view)
    RecyclerView recycleView;
    @BindView(R2.id.load_mask)
    LoadingLayout loadMask;
    @BindView(R2.id.refresh)
    SmartRefreshLayout refresh;
    @BindView(R2.id.search_btn)
    TextView searchBtn;
    @BindView(R2.id.search_txt_delete)
    ImageButton searchDel;
    @BindView(R2.id.search_txt)
    EditText searchTxt;
    @BindView(R2.id.spinner)
    Spinner spinner;

    private View view;

    private String id;

    public void setInstId(String id) {
        this.id = id;
    }

    private SubStreetNewPresenter mPresenter;

    private CommonAdapter commonAdapter;

    private List<PracticeListBean> mDataList = new ArrayList<>();

    private List<PracticeListBean> indexList = new ArrayList<>();

    private String type = "";

    private int page = 1;

    private String keyword = "";

    private boolean isSearchModel = false;

    private int volStatus;

    private String volId;

    public void setVolId(String volId) {
        this.volId = volId;
    }

    public void setVolStatus(int volStatus) {
        this.volStatus = volStatus;
    }



    @Override
    protected View createView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        return view = inflater.inflate(R.layout.practice_fragment_substreet_new, null);
    }

    @Override
    protected void create() {
        mPresenter = new SubStreetNewPresenter(this);
        loadData();
    }

    @Override
    public void initImmersionBar() {

    }

    @Override
    protected void setListener() {
        setListeners();
    }

    @Override
    protected void onFirstVisible() {

    }

    @Override
    protected void onVisible() {

    }

    @Override
    protected void onHide() {

    }

    public static SubStreetNewFragment newInstance(String id, String volId, int volStatus) {
        SubStreetNewFragment fragment = new SubStreetNewFragment();
        fragment.setInstId(id);
        fragment.setVolStatus(volStatus);
        fragment.setVolId(volId);
        return fragment;
    }


    /**
     * 加载数据
     */
    private void loadData() {
        //下拉刷新
        initView();
    }




    private void initView() {
        loadMask.setStatus(LoadingLayout.Loading);

        ArrayAdapter adapter = ArrayAdapter.createFromResource(getContext(), R.array.practice_practice_street, R.layout.practice_spinner_search_layout);
        adapter.setDropDownViewResource(R.layout.practice_spinner_item_layout);
        spinner.setPopupBackgroundResource(R.drawable.practice_spinner_search_bg);
        spinner.setDropDownVerticalOffset(StringUtils.dip2px(getContext(), 25));
        spinner.setBackgroundColor(0x0);
        spinner.setAdapter(adapter);

        refresh.setRefreshHeader(new MaterialHeader(getContext()));
        refresh.setRefreshFooter(new ClassicsFooter(getContext()));
        refresh.setEnableLoadMore(true);

        //设置布局管理器
        recycleView.setLayoutManager(new StaggeredGridLayoutManager(2, StaggeredGridLayoutManager.VERTICAL));

        recycleView.setAdapter(commonAdapter = new CommonAdapter<PracticeListBean>(getContext(), R.layout.practice_item_street_list_new, mDataList) {
            @Override
            protected void convert(ViewHolder holder, PracticeListBean bean, int position) {
                ImageView cover = holder.getView(R.id.cover);
                Glide.with(getContext().getApplicationContext())
                        .load(bean.getLogo())
                        .apply(new RequestOptions().placeholder(R.drawable.cover_normal_default).error(R.drawable.cover_normal_default))
                        .into(cover);

                holder.setText(R.id.title, bean.getName());

                holder.setText(R.id.score_num, bean.getScore() + "");

                holder.setText(R.id.act_num, bean.getActTotal() + "");

                holder.setText(R.id.vol_num, bean.getVolTotal() + "");

                holder.setText(R.id.address, "地址：" + bean.getAddress());

                holder.setText(R.id.phone, "电话：" + bean.getTelephoneNum());


                if (bean.getAct() != null && bean.getAct().getStatus() != null) {
                    holder.setVisible(R.id.act_layout, true);
                    switch (bean.getAct().getStatus()) {
                        case "NOT_BEGIN":
                            holder.setText(R.id.status, "未开始：");
                            break;
                        case "RECRUIT":
                            holder.setText(R.id.status, "招募中：");
                            break;
                        case "SERVICE":
                            holder.setText(R.id.status, "服务中：");
                            break;
                        case "BEGINNING":
                            holder.setText(R.id.status, "进行中：");
                            break;
                        case "END":
                            holder.setText(R.id.status, "已结束：");
                            break;
                        default:
                            break;
                    }
                    holder.setText(R.id.act_title, bean.getAct().getName());
                } else {
                    holder.setVisible(R.id.act_layout, false);
                }

            }
        });

        mPresenter.getList(id, type, page + "");
    }

    @SuppressLint("ClickableViewAccessibility")
    private void setListeners() {
        loadMask.setOnReloadListener(new LoadingLayout.OnReloadListener() {
            @Override
            public void onReload(View v) {
                loadMask.setReloadButtonText("加载中...");
                if (isSearchModel) {
                    mPresenter.doSearch(keyword, type);
                } else {
                    page = 1;
                    mPresenter.getList(id, type, page + "");
                }
            }
        });

        refresh.setOnRefreshListener(new OnRefreshListener() {
            @Override
            public void onRefresh(@NonNull RefreshLayout refreshLayout) {
                if (isSearchModel) {
                    mPresenter.doSearch(keyword, type);
                } else {
                    page = 1;
                    mPresenter.getList(id, type, page + "");
                }
            }
        });

        refresh.setOnLoadMoreListener(new OnLoadMoreListener() {
            @Override
            public void onLoadMore(@NonNull RefreshLayout refreshLayout) {
                mPresenter.getList(id, type, page + "");
            }
        });

        commonAdapter.setOnItemClickListener(new MultiItemTypeAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(View view, RecyclerView.ViewHolder holder, int position) {
                Bundle bundle = new Bundle();
                bundle.putString("instId", id);
                bundle.putString("streetId", mDataList.get(position).getId() + "");
                bundle.putString("title", mDataList.get(position).getName());
                bundle.putString("volId", volId);
                bundle.putInt("status", volStatus);
                RouterManager.router(ARouterPathConstant.PRACTICE_STREET_DETAIL,bundle);

            }

            @Override
            public boolean onItemLongClick(View view, RecyclerView.ViewHolder holder, int position) {
                return false;
            }
        });

        searchTxt.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {

            }

            @Override
            public void afterTextChanged(Editable s) {
                keyword = s.toString();
                if (StringUtils.isNotEmpty(s.toString()) && s.toString().trim().length() > 0) {
                    searchBtn.setText("搜索");
                    searchDel.setVisibility(View.VISIBLE);
                } else {
                    searchBtn.setText("取消");
                    searchDel.setVisibility(View.GONE);
                }
            }
        });

        searchTxt.setOnEditorActionListener(new TextView.OnEditorActionListener() {
            @Override
            public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
                if (actionId == EditorInfo.IME_ACTION_SEARCH) {//按下搜索
                    keyword = searchTxt.getText().toString();
                    mPresenter.doSearch(keyword, type);
                    hideInput();
                }
                return false;//返回true，保留软键盘。false，隐藏软键盘
            }

        });

        spinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
            @Override
            public void onItemSelected(AdapterView<?> parent, View view, int position, long id1) {
                page = 1;
                switch (position) {
                    case 0:
                        type = "";//全部
                        break;
                    case 1:
                        type = "0"; //实践站
                        break;
                    case 2:
                        type = "1";//实践所
                        break;
                    case 3:
                        type = "2";//企业服务站
                        break;
                    default:
                        type = "";
                        break;
                }
                if (isSearchModel) {
                    mPresenter.doSearch(keyword, type);
                } else {
                    mPresenter.getList(id, type, page + "");
                }

            }

            @Override
            public void onNothingSelected(AdapterView<?> parent) {

            }
        });
    }

    @OnClick({R2.id.search_btn, R2.id.search_txt_delete})
    public void onViewClicked(View view) {
        int viewId = view.getId();
        if (viewId == R.id.search_btn) {
            if (searchBtn.getText().toString().equals("搜索")) {
                hideInput();
                isSearchModel = true;
                refresh.setEnableLoadMore(false);
                if (StringUtils.isNotEmpty(keyword)) {
                    mPresenter.doSearch(keyword, type);
                } else {
                    isSearchModel = false;
                    showToast("搜索内容不能为空！", 4);
                }
            } else {
                if (indexList != null && indexList.size() > 0) {
                    loadMask.setStatus(LoadingLayout.Success);
                }
                isSearchModel = false;
                refresh.setEnableLoadMore(true);
                mDataList.clear();
                mDataList.addAll(indexList);
                commonAdapter.notifyDataSetChanged();
            }
        } else if (viewId == R.id.search_txt_delete) {
            searchTxt.setText("");
        }
    }


    @Override
    public void setList(List<PracticeListBean> beanList, boolean isMore) {
        loadMask.setStatus(LoadingLayout.Success);
        loadMask.setReloadButtonText("点击重试~");
        indexList.clear();
        if (isMore) {
            refresh.finishLoadMore();
        } else {
            loadMask.setStatus(LoadingLayout.Success);
            refresh.finishRefresh();
            mDataList.clear();
        }
        page++;
        mDataList.addAll(beanList);
        indexList.addAll(mDataList);
        commonAdapter.notifyDataSetChanged();
    }

    @Override
    public void setError(String msg, boolean isMore) {
        loadMask.setReloadButtonText("点击重试~");
        if (isMore) {
            refresh.finishLoadMore();
            if (!NetUtil.isNetworkAvalible(getContext())) {
                showToast("网络异常，请检查您的网络！", 4);
            }
        } else {
            refresh.finishRefresh();
            loadMask.setStatus(LoadingLayout.Error);
            if (!NetUtil.isNetworkAvalible(getContext())) {
                loadMask.setErrorImage(R.drawable.error_network);
                loadMask.setErrorText("网络异常，请检查您的网络！");
            } else if (msg.contains("暂无")) {
                loadMask.setErrorImage(R.drawable.empty_content);
                loadMask.setErrorText(msg);
            } else {
                loadMask.setErrorImage(R.drawable.error_content);
                loadMask.setErrorText(msg);
            }
        }
    }

    @Override
    public void setSearch(List<PracticeListBean> beanList) {
        loadMask.setStatus(LoadingLayout.Success);
        loadMask.setReloadButtonText("点击重试~");
        mDataList.clear();
        mDataList.addAll(beanList);
        commonAdapter.notifyDataSetChanged();
    }

}
